import React, { Component } from 'react';
import {
    View,
    StyleSheet,
    AppRegistry,
    TouchableHighlight,
    TouchableOpacity,
    Image,
    Dimensions,
    Platform,
    RefreshControl,
    DeviceEventEmitter,
    Alert
} from 'react-native';


import { Container, Content, Card, CardItem, Thumbnail, Text, Button, Icon, Spinner } from 'native-base';
import { NavigationActions } from 'react-navigation';
import { connect } from 'react-redux';
import Message from '../../net/message.js';
import CourseMessage from '../../db/course_message_table.js';

const { width, height } = Dimensions.get('window');
const marginTop = Platform.OS === 'ios' ? 20 : 0;
let table_list_array = [];
let sign_status = ['签到', '已签到'];
// var MiPushModule = require('../../DemoMessageReceiver');

class school_message_list extends Component {

    //mixins:[Subscribable.Mixin];  
    //   componentWillMount(){ 
    //                     DeviceEventEmitter.addListener('SchoolMessageInteract', function(e: Event) {  
    //                          alert("event listener success");  
    //                        }); 
    //                      }

    static navigationOptions = ({ navigation }) => ({
        title: navigation.state.params.title,
    });
    constructor(props) {
        super(props);
        this.state = {
            course_list_array: null,
            userid: null,
            signteststatus: ['签到', '已签到'],
            sign: '签到',
            signed: '已签到',
        };
    }
    render_card(array) {
        const { navigate } = this.props.navigation;
        return array.map((v, i) => {
            if (v.messageType == "SignIn") {
                return (
                    <Card key={i}>
                        <CardItem>
                            <Text note style={StyleSheet.flatten(styles.time_style)}>
                                {v.sendtime}
                            </Text>
                        </CardItem>
                        <CardItem>
                            <View style={StyleSheet.flatten(styles.cardview_style)}>
                                <Text style={StyleSheet.flatten(styles.title_style)}>{decodeURI(v.coursetitle)}</Text>
                                <Text style={StyleSheet.flatten(styles.content_style)}>授课教师：{decodeURI(v.teacher)}</Text>
                                <View style={{ flexDirection: 'row', justifyContent: 'space-around' }}>
                                    <Button info style={StyleSheet.flatten(styles.signbutton_style)} onPress={
                                        () => {
                                            let mess = new Message();
                                            let data = mess.new_sign(this.state.userid, v.moocCourseID);
                                            data.then((result) => {
                                                console.log('result:----', result);
                                                // Alert.alert('温馨提醒:', result.messageInfo);
                                                if (result.errorCode == 0) {
                                                    Alert.alert('温馨提醒:', '签到成功');
                                                    this.setState({ sign: '已签到', })
                                                } else {
                                                    if (result.messageInfo == 'SignIn Closed' || result.messageInfo == 'SignIn has not been opened') {
                                                        console.log('储相瑞java')
                                                        Alert.alert('温馨提醒:', '签到未开启');
                                                    }
                                                    else if (result.messageInfo == 'Course Closed' || result.messageInfo == 'The Course has not been opened') {
                                                        Alert.alert('温馨提醒:', '课堂未开启');
                                                    }
                                                    else if (result.messageInfo == 'SignIn Again') {
                                                        Alert.alert('温馨提醒:', '不允许重复签到');
                                                    }
                                                    else if (result.messageInfo == 'not InteractionCourse') {
                                                        Alert.alert('温馨提醒:', '此课程为非交互课程');
                                                    }                                       
                                                }
                                                if (result.messageInfo == 'SignIn Success') {
                                                    //设置都已签到，需要改进；但一般来说都是推送一条消息，所以暂时可以。
                                                    this.setState({ signteststatus: ['已签到', '已签到'] });
                                                }
                                            });
                                            let message_info = new CourseMessage();
                                            message_info.MessageSignIn(v.id);

                                        }
                                    }>
                                        <Icon name="hand" />
                                        <Text>{this.state.signteststatus[v.singstatus]}</Text>
                                    </Button>
                                </View>
                            </View>
                        </CardItem>

                    </Card>
                );

            }
            else if (v.messageType == "interaction") {
                return (
                    <Card key={i}>
                        <CardItem>
                            <Text note style={StyleSheet.flatten(styles.time_style)}>
                                {v.sendtime}
                            </Text>
                        </CardItem>
                        <CardItem>
                            <View style={StyleSheet.flatten(styles.cardview_style)}>
                                <Text style={StyleSheet.flatten(styles.title_style)}>{decodeURI(v.coursetitle)}</Text>
                                <Text style={StyleSheet.flatten(styles.content_style)}>授课教师：{decodeURI(v.teacher)} </Text>
                                <View style={{ flexDirection: 'row', justifyContent: 'space-around' }}>
                                    <Button info style={StyleSheet.flatten(styles.signbutton_style)} onPress={() => {
                                        //将对应缓存数据抛redux
                                        const { InteractionPushSubjectId } = this.props;
                                        InteractionPushSubjectId({
                                            type: 'InteractionPushSubjectId',
                                            payload: {
                                                subjectId: v.SubjectID,
                                                OnlineClassID: v.OnlineClassID,
                                                //题目推送号
                                                SendSubjectID: v.SendSubjectID,
                                            }
                                        });
                                        navigate('QuestionStudent_course', { title: decodeURI(v.coursetitle) })
                                    }

                                    }
                                    >
                                        <Icon name="hand" />
                                        <Text>交互</Text>
                                    </Button>
                                </View>
                            </View>
                        </CardItem>
                    </Card>
                );
            }
        })
    }
    render() {
        if (!this.state.course_list_array) {
            return this.renderLoadingView();
        }
        return (
            <Container>
                <Content refreshControl={<RefreshControl refreshing={false} />} scrollEnabled={true}>
                    {this.render_card(this.state.course_list_array)}
                </Content>
            </Container>
        );
    }
    renderLoadingView() {
        return (
            <Container>
                <Content>
                    {/*<Spinner color='green' />*/}
                </Content>
            </Container>
        );
    }

    async componentWillMount() {
        const { course_info } = this.props;
        const login_info = this.props.login_info;

        let message_info = new CourseMessage();
        try {
            let info = await message_info.queryAllCourseMessage();
            table_list_array.splice(0, table_list_array.length);//清空数组 
            for (let i = 0; i < info.length; i++) {
                // console.log('lenth;',i);
                table_list_array[i] = info.item(i);
            }
            // console.log('message_count-----:',info.length);
            // console.log('course_message------------:',info.item(2).coursetitle);
            // console.log('course_message_info_item------------:',info.item(2));
            // console.log('course_message_info------------:',info);
            // console.log('table_list_array------------:',table_list_array);
        } catch (e) {
            console.log("error", e);
        }

        console.log('userid-id:', login_info.userName);
        this.setState({ course_list_array: table_list_array, userid: login_info.userName });
        // this.setState({ course_list_array: course_info.course_data ,userid:login_info.userName});
    }
}

const styles = StyleSheet.create({
    time_style: {
        width: width,
        textAlign: 'center',
        paddingRight: '7%',
    },
    cardview_style: {
        width: width - 20,
        height: height / 4,
        marginLeft: -10,
        backgroundColor: 'white',
        borderWidth: 1,
        borderColor: 'grey'
    },
    title_style: {
        marginTop: 10,
        marginLeft: 10
    },
    content_style: {
        fontSize: 12,
        marginLeft: 10,
        color: 'grey',
        marginTop: 10
    },
    signbutton_style: {
        marginTop: 10,
        marginLeft: 10,
        backgroundColor:'#F0AD4E'

    },
    interbutton_style: {
        marginTop: 10,
        marginRight: 10,
    }


});

function mapStateToProps(state) {
    return {
        course_info: state.message.course_info,
        login_info: state.login.login_info
    }
}

//将获取的数据抛给reducers
function mapDispatchToProps(dispatch) {
    return {
        InteractionPushSubjectId: (state) => dispatch(state),
    }
}

const SchoolMessageInteract = connect(
    mapStateToProps,
    mapDispatchToProps
)(school_message_list)

export default SchoolMessageInteract;
AppRegistry.registerComponent('SchoolMessageInteract', () => SchoolMessageInteract);
